﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DemoUserInfo.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using PagedList;

namespace DemoUserInfo.Controllers
{
    public class ArticlesController : Controller
    {
        public ArticleDbContext db = new ArticleDbContext();
        private ArticelNums CountNums = new ArticelNums();

        // GET: Articles
        public ActionResult Index(string tag, int? page)
        {
            var articles = from a in db.Articles select a;
            var tags = new List<string>();
            foreach (var temo in articles)
            {
                if (!tags.Contains(temo.Tag)) tags.Add(temo.Tag);
            }
            if (!String.IsNullOrEmpty(tag))
            {
                articles = articles.Where(a => a.Tag.Equals(tag));
            }
            ViewData["tags"] = tags;
            articles = articles.OrderByDescending(a => a.Date);
            int pageSize = 18;
            int pageNumber = (page ?? 1);
            return View(articles.ToPagedList(pageNumber, pageSize));
        }

        // GET: Articles/Details/5
        [Authorize(Roles = "User")]
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            ViewBag.id = id;
            ViewBag.src = article.Source;
            ViewBag.titleImg = article.TitleImgSrc;
            return View(article);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [Authorize(Roles = "User" )]
        public ActionResult Create([Bind(Include = "Title,Introduction,Tag")] Article article, HttpPostedFileBase titleImg, string mainArc, string returnUrl)
        {

            if (ModelState.IsValid && mainArc != null && titleImg != null)
            {
                string uploadFolder1 = "/Upload/Draft/" + DateTime.Now.ToString("yyyyMM") + "/";
                string uploadFolder2 = "/Upload/TitleImg/" + DateTime.Now.ToString("yyyyMM") + "/";
                string arcName = DateTime.Now.ToString("ddHHmmssff") + ".cshtml";
                string titleImgName = DateTime.Now.ToString("ddHHmmssff")
                    + titleImg.FileName.Substring(titleImg.FileName.LastIndexOf('.'));
                string uploadPath1 = Server.MapPath(uploadFolder1);
                string uploadPath2 = Server.MapPath(uploadFolder2);
                var currentUserId = User.Identity.GetUserId();
                var context = new ApplicationDbContext();
                var temp = context.Users.Where(u => u.Id == currentUserId);
                var user = temp.FirstOrDefault();
                if (!Directory.Exists(uploadPath1))
                {
                    Directory.CreateDirectory(uploadPath1);
                }
                if (!Directory.Exists(uploadPath2))
                {
                    Directory.CreateDirectory(uploadPath2);
                }
                System.IO.File.WriteAllText(Path.Combine(uploadPath1, arcName), mainArc, Encoding.UTF8);
                titleImg.SaveAs(Path.Combine(uploadPath2, titleImgName));
                article.Id = CountNums.Cnt;
                article.Date = DateTime.Now;
                article.Author = user.NickName;
                article.Source = Path.Combine(uploadFolder1, arcName);
                article.TitleImgSrc = Path.Combine(uploadFolder2, titleImgName);
                db.Articles.Add(article);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(article);
        }

        // GET: Articles/Delete/5
        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Article article = db.Articles.Find(id);
            if (article == null)
            {
                return HttpNotFound();
            }
            return View(article);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult DeleteConfirmed(int id)
        {
            Article article = db.Articles.Find(id);
            if (article != null)
            {
                db.Articles.Remove(article);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        [Authorize(Roles = "Admin")]
        public ActionResult DelList(string search, int? page)
        {
            var articles = from a in db.Articles select a;
            var tags = new List<string>();
            foreach (var temo in articles)
            {
                if (!tags.Contains(temo.Tag)) tags.Add(temo.Tag);
            }
            if (!String.IsNullOrEmpty(search))
            {
                articles = articles.Where(a => a.Title.Contains(search));
            }
            articles = articles.OrderByDescending(a => a.Date);
            int pageSize = 18;
            int pageNumber = (page ?? 1);
            return View(articles.ToPagedList(pageNumber, pageSize));
        }

    }
}
